<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">





  <link rel="alternate" href="/atom.xml" title="renhao" type="application/atom+xml">






<meta name="description" content="本文总结下浏览器中的回流重绘知识">
<meta property="og:type" content="article">
<meta property="og:title" content="浏览器中的 painting 和 layout">
<meta property="og:url" content="https://huangrenhao.gitee.io/2020/09/03/browser-repaint-reflow/index.html">
<meta property="og:site_name" content="renhao">
<meta property="og:description" content="本文总结下浏览器中的回流重绘知识">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-09-24T04:00:30.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="浏览器中的 painting 和 layout">
<meta name="twitter:description" content="本文总结下浏览器中的回流重绘知识">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://huangrenhao.gitee.io/2020/09/03/browser-repaint-reflow/">





  <title>浏览器中的 painting 和 layout | renhao</title>
  








<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">renhao</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://huangrenhao.gitee.io/2020/09/03/browser-repaint-reflow/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="renhao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="renhao">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">浏览器中的 painting 和 layout</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-09-03T16:40:43+08:00">
                2020-09-03
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/browser/" itemprop="url" rel="index">
                    <span itemprop="name">browser</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/09/03/browser-repaint-reflow/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2020/09/03/browser-repaint-reflow/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.6k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文总结下浏览器中的回流重绘知识<a id="more"></a></p>
<h2 id="重绘-painting-和回流-layout（重排）"><a href="#重绘-painting-和回流-layout（重排）" class="headerlink" title="重绘 painting 和回流 layout（重排）"></a>重绘 painting 和回流 layout（重排）</h2><p>重绘是屏幕的一部分要重画，但是元素的几何尺寸没有变，如改变某个元素的背景色、文字颜色、边框颜色等等不影响它周围或内部布局的属性。回流是布局或者几何属性需要改变。回流必定发生重绘，重绘不一定会引发回流。回流所需成本比重绘高的多，改变深层次的节点很可能导致父节点的一系列回流。reflow 会从 <code>&lt;html&gt;</code> 这个 root frame 开始递归往下，依次计算所有的结点几何尺寸和位置。reflow 几乎是无法避免的。现在界面上流行的一些效果，比如树状目录的折叠、展开（实质上是元素的显 示与隐藏）等，都将引起浏览器的 reflow。鼠标滑过、点击……只要这些行为引起了页面上某些元素的占位面积、定位方式、边距等属性的变化，都会引起它内部、周围甚至整个页面的重新渲 染。通常我们都无法预估浏览器到底会 reflow 哪一部分的代码，它们都彼此相互影响着。</p>
<h3 id="触发页面回流"><a href="#触发页面回流" class="headerlink" title="触发页面回流"></a>触发页面回流</h3><p>回流主要计算节点的位置和几何信息，故触发回流方式为布局或几何信息变化时</p>
<ul>
<li>添加或删除可见 dom 元素</li>
<li>元素的位置发生变化</li>
<li>元素的尺寸发生变化（外边距、内边距、边框大小、高宽等）</li>
<li>内容发生变化（文本变化或图片被不同尺寸图片替代）</li>
<li>页面一开始渲染</li>
<li>浏览器窗口尺寸变化</li>
</ul>
<h3 id="触发页面重绘"><a href="#触发页面重绘" class="headerlink" title="触发页面重绘"></a>触发页面重绘</h3><ul>
<li><p>color</p>
</li>
<li><p>border-style<br>border-radius</p>
</li>
<li><p>visibility</p>
</li>
<li><p>text-decoration</p>
</li>
<li><p>background<br>background-image<br>background-position<br>background-repeat<br>background-size</p>
</li>
<li><p>outline<br>outline-style</p>
<p>outline-color<br>outline-width</p>
</li>
<li><p>box-shadow</p>
</li>
</ul>
<h3 id="浏览器的优化机制"><a href="#浏览器的优化机制" class="headerlink" title="浏览器的优化机制"></a>浏览器的优化机制</h3><p>大多数浏览器都会通过队列化修改并批量执行来优化重排过程。浏览器会将修改操作放入到队列里，直到过了一段时间或者操作达到了一个阈值，才清空队列。但<strong>当获取布局信息的操作的时候，会强制队列刷新</strong>，比如访问以下属性或者使用以下方法：（因为这些属性和方法都需要返回最新的布局信息）</p>
<ul>
<li>offsetTop、offsetLeft、offsetWidth、offsetHeight</li>
<li>scrollTop、scrollLeft、scrollWidth、scrollHeight</li>
<li>clientTop、clientLeft、clientWidth、clientHeight</li>
<li>getComputedStyle()</li>
<li>getBoundingClientRect</li>
</ul>
<h3 id="减少回流和重绘："><a href="#减少回流和重绘：" class="headerlink" title="减少回流和重绘："></a>减少回流和重绘：</h3><ul>
<li><p>减少回流重绘发生次数：合并多次对样式和dom 的修改，一次处理。</p>
<ul>
<li>使用 cssText</li>
<li>修改 class</li>
</ul>
</li>
<li><p>批量修改 dom：不要把 DOM 节点的属性值放在一个循环里当成循环里的变量</p>
<p>浏览器有一个回流的缓冲机制，即多个回流会保存在一个栈里面，当这个栈满了浏览器便会一次性触发所有样式的更改且刷新这个栈。但是如果你多次获取这些元素的实际样式，浏览器为了给你一个准确的答案便会不停刷新这个缓冲栈，导致页面回流增加。所以为了避免这个问题，应该用一个变量保存在循环体外。可以通过 cloneNode 将要在循环中操作的 dom 节点复制一份或者操作 fragment</p>
</li>
<li><p>复杂动画</p>
<ul>
<li>使用绝对定位脱离文档流，否则会引起父元素及后续元素频繁的回流</li>
<li>将频繁运行的动画变为一个新的复合图层，图层能够阻止该节点回流影响别的元素。</li>
</ul>
</li>
<li><p>css3 硬件加速：不需要回流重绘，<strong>使用css3硬件加速，可以让transform、opacity、filters这些动画不会引起回流重绘 。但是对于动画的其它属性，比如background-color这些，还是会引起回流重绘的，不过它还是可以提升这些动画的性能。</strong>常见的触发硬件加速的css属性：</p>
<ul>
<li>transform</li>
<li>opacity</li>
<li>filters</li>
<li>Will-change</li>
</ul>
<p>缺点：</p>
<ul>
<li>为太多元素使用css3硬件加速，会导致内存占用较大，会有性能问题。</li>
<li>在GPU渲染字体会导致抗锯齿无效。这是因为GPU和CPU的算法不同。因此如果不在动画结束的时候关闭硬件加速，会产生字体模糊。</li>
</ul>
</li>
<li><p>使用 visibility 替换 <code>display:none</code>，因为前者只会引起重绘，后者会引发回流（改变了布局）</p>
</li>
<li><p>用opacity替代visibility，但是要同时有translate3d 或 translateZ 这些可以创建的图层的属性存在才可以阻止回流</p>
<p>opacity 不会触发回流，更不会触发重绘,没有paint的过程，因为paint的过程是生成图层，但是opacity实际上是直接改变的图层的alpha通道，所以不涉及图层的重绘</p>
<blockquote>
<p>visibility 为 hidden 不会触发元素已经绑定的事件，opacity 为 0 还是会触发相应的事件</p>
</blockquote>
</li>
<li><p>table布局中一个小改动可能造成整个 table 重新布局，尽量不使用table</p>
</li>
<li><p>动画速度越快回流次数越多，可以选择使用 requestAnimationFrame</p>
</li>
<li><p>CSS 选择符从右向左匹配查找，避免 DOM 深度过深</p>
</li>
<li><p>将使用 top 改变位置改为用 <code>transform:translate3d(tx,ty,0)</code> 实现（新建图层）</p>
</li>
</ul>
<blockquote>
<h2 id="Chrome创建自动创建图层的条件"><a href="#Chrome创建自动创建图层的条件" class="headerlink" title="Chrome创建自动创建图层的条件"></a>Chrome创建自动创建图层的条件</h2><ul>
<li>3D或透视变换（perspective transform）CSS属性</li>
<li>使用加速视频解码的<code>&lt;video&gt;</code>节点</li>
<li>拥有3D（WebGL）上下文或加速的2D上下文的<code>&lt;canvas&gt;</code>节点</li>
<li>混合插件（如Flash）</li>
<li>对自己的opacity做CSS动画或使用一个动画webkit变换的元素</li>
<li>拥有加速CSS过滤器的元素</li>
<li>元素有一个包含复合层的后代节点（一个元素拥有一个子元素，该子元素在自己的层里）</li>
<li>元素有一个z-index较低且包含一个复合层的兄弟元素（换句话说就是该元素在复合层上面渲染）</li>
</ul>
<p>Chrome浏览器的more tools下面的Layers能查看图层信息，rendering能查看浏览器页面正在重绘的元素。</p>
<p>用图层可以减少重绘和回流，但是图层会有合成的消耗</p>
</blockquote>
<blockquote>
<p><a href="https://www.cnblogs.com/QianDingwei/p/11028362.html" target="_blank" rel="noopener">参考</a></p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/09/03/webpack-loader-plugin/" rel="next" title="webpack 中的 loader 与 plugin">
                <i class="fa fa-chevron-left"></i> webpack 中的 loader 与 plugin
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/09/03/browser-yi-dong-duan-gua-pei/" rel="prev" title="移动端适配">
                移动端适配 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">renhao</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">94</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#重绘-painting-和回流-layout（重排）"><span class="nav-number">1.</span> <span class="nav-text">重绘 painting 和回流 layout（重排）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#触发页面回流"><span class="nav-number">1.1.</span> <span class="nav-text">触发页面回流</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#触发页面重绘"><span class="nav-number">1.2.</span> <span class="nav-text">触发页面重绘</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#浏览器的优化机制"><span class="nav-number">1.3.</span> <span class="nav-text">浏览器的优化机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#减少回流和重绘："><span class="nav-number">1.4.</span> <span class="nav-text">减少回流和重绘：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Chrome创建自动创建图层的条件"><span class="nav-number">2.</span> <span class="nav-text">Chrome创建自动创建图层的条件</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">renhao</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">265.9k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '2P1xqUWiCoNm14MH4yhURlJi-gzGzoHsz',
        appKey: 'uJN0uagHIVgXtBO1OuLV9Ban',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
